Python list index方法:查询具有特定值的元素的索引 您所在的位置:网站首页 python 字符串数组索引 Python list index方法:查询具有特定值的元素的索引

Python list index方法:查询具有特定值的元素的索引

2023-11-09 02:09| 来源: 网络整理| 查看: 265

目录

描述

语法和参数

返回值

使用示例

在列表中查询

在列表内的某个区间内查询

注意事项

要查询的元素在列表中不存在

要查询的元素在列表中存在多次

start大于end

start和end超出列表有效范围

描述

Python list.index方法返回某一个值的元素位于列表中的索引。

语法和参数 list.index(element, start, end) 名称含义element要查询的元素值,不可省略的参数,可以是任意类型的对象实例start可选整型参数,查找的起始位置。end可选整型参数,查找的结束位置。

返回值

int。list.index方法返回参数值所在列表的索引。

使用示例 在列表中查询

index方法返回参数所在列表中的索引。

>>> demo = ["running", "pending", "error"] >>> demo.index("running") 0 在列表内的某个区间内查询

默认情况下index方法在整个列表中搜索要查询的值。使用start和end 参数可以在列表中的某个区间搜索。当end值省略时,表示从start值对应的索引开始搜索,一直到列表的最后一个元素。当start,end值都存在时,表示从[start, end-1]闭区间内搜索。

>>> demo = ["a", "p", "p", "l", "e"] >>> demo.index("p", 2) 2 >>> demo.index("p", 3, 4) Traceback (most recent call last): File "", line 1, in ValueError: 'p' is not in list

注意事项 要查询的元素在列表中不存在

当要查询的元素在列表中不存在时,index方法抛出ValueError异常。

>>> demo = ["running", "pending", "error"] >>> demo.index("finish") Traceback (most recent call last): File "", line 1, in ValueError: 'finish' is not in list 要查询的元素在列表中存在多次

当要查询的元素在列表中存在多次时,index方法返回最靠近列表头的元素的索引。

>>> demo = ["running", "pending", "error", "error"] >>> demo.index("error") 2

因此当值在列表中存在多次时,index方法仅能返回最靠近列表头的元素的索引值,而不能将所有匹配值的索引返回。

start大于end

由于start和end可正可负,但它们在真实逻辑上表示的是列表的索引下标。当start对应的逻辑下标在end对应的逻辑下标右边或者重合时,index方法抛出ValueError异常。例如下面的代码,虽然start的值(1)大于end的值(-1),但是end值表示的逻辑索引为4,位于start的右边,因此index可以正确返回。

>>> demo = ["a", "p", "p", "l", "e"] >>> demo.index("l", 1, -1) 3

下面的代码start值表示的逻辑索引分别在end值表示的逻辑索引的右边,重合。在这些情况下index方法抛出ValueError异常。

>>> demo = ["a", "p", "p", "l", "e"] >>> demo.index("p", 3, 1) Traceback (most recent call last): File "", line 1, in ValueError: 'p' is not in list >>> demo.index("p", 1, 1) Traceback (most recent call last): File "", line 1, in ValueError: 'p' is not in list

start和end超出列表有效范围

start和end的值涉及到以下几种可能性:

A. start和end均在列表长度有效范围中;

B. start在有效范围中,而end不在;

C. start不在有效范围中,而end在;

D. start和end均不在有效范围中。

对于场景A,我们已经论述过了,如果start和end均在长度有效范围内,index会返回被查找元素的下标,或者抛出ValueError异常。

当start和end超出列表长度有效范围后,index方法不会报错,而是将超出长度的start或end视为最大长度值,即列表最后一个元素的下标+1。

>>> demo = ["a", "p", "p", "l", "e"] >>> demo.index("e", 0, 400) 4

在上面的代码中,end值为400,这显然超出了列表的最大范围。但是start值为0,在列表的长度范围中,因此index方法从第0个元素开始搜索元素"e",一直到最后一个元素。

对于C和D场景,index方法会抛出ValueError异常。

>>> demo = ["a", "p", "p", "l", "e"] >>> demo.index("e", 500, 2) Traceback (most recent call last): File "", line 1, in ValueError: 'e' is not in list >>> >>> demo.index("e", 400, 500) Traceback (most recent call last): File "", line 1, in ValueError: 'e' is not in list



【本文地址】

公司简介

联系我们

今日新闻

    推荐新闻

      专题文章
        CopyRight 2018-2019 实验室设备网 版权所有